<!-- 地址簿组件 语音识别 图片识别 黏贴识别 省市区联动-->
<template>
  <nut-popup position="bottom" closeable round :style="{ height: '70%' }" @click-close-icon="sendAddressFormMsg" v-model:visible="props.showRound">
    <nut-notify v-model:visible="toastShow" :msg="noticeMsg" />
    <nut-cell :title="`填写${props.formType}信息`"></nut-cell>
    <!-- 识别  -->
    <view class="sb">
      <nut-textarea style="height: 100rpx" v-model="autoAddressInfo" placeholder="请粘贴或输入文本，点击填”识别“自动识别姓名、联系方式和地址" />
      <view class="row">
        <view class="one">
          <image src="../../assets/images/sendAddress/fahuoxinxi_icon_yuying.png"></image>
          <view @click="sounds" class="text">语音识别</view>
          <image src="../../assets/images/sendAddress/fahuoxinxi_icon_tupian.png" style="margin-left: 48rpx"></image>
          <view class="text" @click="upLoadImg">图片识别</view>
        </view>
        <view class="tow">
          <view class="button" @click="doToAddress">{{ identify }}</view>
        </view>
      </view>
    </view>
    <!-- 识别  -->
    <view class="address_del">
      <nut-form :model-value="addressForm">
        <view class="rows">
          <nut-form-item label="真实姓名" label-align="center">
            <nut-input v-model="addressForm.name" placeholder="请填写真实姓名" :border="false" />
          </nut-form-item>
        </view>
        <view class="rows">
          <nut-form-item label="联系方式" label-align="center">
            <nut-input v-model="addressForm.phone" placeholder="请填写手机或座机号码" :border="false" />
          </nut-form-item>
        </view>
        <view class="flex-ld">
          <view>
            <view class="rows">
              <nut-form-item label="省/市/区" label-align="center">
                <nut-input v-model="addressForm.provinceAdd" placeholder="请选择省/市/区" :border="false" @click="showProvince = true" />
              </nut-form-item>
            </view>
            <view class="rows">
              <nut-form-item label="详细地址" label-align="center">
                <nut-input v-model="addressForm.address" placeholder="请填写精确到门牌的详细地址" :border="false" />
              </nut-form-item>
            </view>
          </view>
          <view class="address_icon" @click="setDestination"></view>
        </view>
      </nut-form>
      <!-- 省市区选择 -->
      <Province @receiveProvinceMsg="closeProvince" :showRound="showProvince" />
    </view>
    <nut-button block type="primary" color="#0966ff" @click="sendAddressFormMsg">确定</nut-button>
  </nut-popup>
  <!-- 语音识别  -->
  <comRecord ref="recordRef" @click="onFinish"></comRecord>
</template>

<script setup lang="ts">
import { onMounted, defineComponent, getCurrentInstance, reactive, ref, watch } from 'vue'
import { getAddressByCode } from '@/@api/wait' // 待确认接口

import Taro from '@tarojs/taro'
import { IconFont } from '@nutui/icons-vue-taro'

import Province from './provinceSelect.vue' // 省市区选择组件

import comRecord from '@/components/comRecord/index.vue'

const props = defineProps(['showRound', 'formType', 'addressBookInit'])

const emit = defineEmits(['receiveAddressForm'])

const addressForm = ref({
  name: '', // 姓名
  phone: '', // 手机号
  address: '', // 详细地址
  provinceAdd: '' // 省市区
  // isdefault: false,
  // id: "",
})

watch(
  () => props.addressBookInit,
  (newVal) => {
    // console.log(newVal, '监听props.addressBookInit')
    addressForm.value.name = props.addressBookInit?.name
    addressForm.value.phone = props.addressBookInit?.phone
    addressForm.value.address = props.addressBookInit?.address
  },
  { deep: true }
)

const toastShow = ref(false) // 提示信息是否显示
const noticeMsg = ref('') // 提示信息数据

const showProvince = ref() // 省市区抽屉显隐

// 关闭省市区抽屉并赋值给地址本抽屉
function closeProvince(msg) {
  // console.log(msg, '拿到省市区选择的信息')
  addressForm.value.provinceAdd = msg
  showProvince.value = false
}

// 选择详细地址
const setDestination = () => {
  Taro.chooseLocation({
    success: function (res) {
      // console.log(res);
      addressForm.value.address = res.address // 地址
      // orderInfo.value.destinationBranchName = res.address
      // orderInfo.value.latitude = res.latitude
      // orderInfo.value.longitude = res.longitude
      GETLNGLAT(res.address)
    },
    fail: function (err) {
      // 处理失败情况
      console.error(err)
    }
  })
}

// 关闭地址本抽屉并赋值
function sendAddressFormMsg() {
  const isFormValid = validateAddressForm(addressForm.value)
  if (isFormValid) {
    // console.log(props.formType, '是什么类型的')
    emit('receiveAddressForm', addressForm.value, props.formType) // 传递地址本表单数据
  } else {
    toastShow.value = true
    noticeMsg.value = '请填写完整信息'
  }
}

function validateAddressForm(form) {
  return Object.values(form).every((value) => value)
}

// 开始

const autoAddressInfo = ref('')
import useUserInfoStore from '@/store/user'

const userStore = useUserInfoStore()

const recordRef = ref<InstanceType<typeof comRecord>>()

import { adjustDistrict } from './sub'
import { $post } from '@/@api/index'

const addressInfo = ref<string[]>([])

if (process.env.TARO_ENV === 'weapp') {
  const { useSoundsTool } = require('@/utils/sound')
  const { requirePlugin } = require('@tarojs/taro')
  const plugin = requirePlugin('WechatSI')
  var manager = plugin.getRecordRecognitionManager()
}

const initRecord = () => {
  manager.onStart = function (res: any) {
    Taro.hideLoading()
    recordRef.value?.onOpen()
  }
  manager.onError = function (res: any) {
    // console.log('error msg', res.msg)
    Taro.showToast({
      title: '语音识别失败'
    })
    //   options.onError(res.msg)
    manager.stop()
  }
  manager.onStop = function (res: any) {
    // console.log("record file path", res.tempFilePath);
    // console.log("result", res.result);
    if (res.result) {
      autoAddressInfo.value = res.result
      Taro.hideLoading()
    } else {
      Taro.showLoading({
        title: '语音识别失败1'
      })
      Taro.hideLoading()
      recordRef.value?.onClose()
    }
  }
}
const sounds = () => {
  Taro.showLoading({
    title: '请稍后'
  })
  manager.start({ lang: 'zh_CN', duration: 30000 })
}

const onFinish = () => {
  recordRef.value?.onClose()
  Taro.showLoading({
    title: '识别中'
  })
  manager.stop()
}
const identify = ref('粘贴并识别')

watch(autoAddressInfo, (v) => {
  if (myEnvironment === 'weapp') {
    if (v) {
      identify.value = '识别'
    } else {
      identify.value = '粘贴并识别'
    }
  }
})

const doToAddress = () => {
  if (identify.value == '粘贴并识别') {
    Taro.getClipboardData({
      success(res) {
        Taro.hideToast()
        // console.log(res.data)
        autoAddressInfo.value = res.data
      }
    })
  } else {
    autoAddress()
  }
}
async function autoAddress() {
  if (!autoAddressInfo.value) {
    return Taro.showToast({
      icon: 'error',
      title: '请填写地址'
    })
  }

  Taro.login({
    success: function (res) {
      if (res.code) {
        console.log(res.code, '获取code')
        //发起网络请求
        // 使用 Taro 发起网络请求
        Taro.request({
          url: `http://it.shenghui56.com/ywhserver/selfmachine-system/workerIndex/getOpenId?code=${res.code}`,
          method: 'GET',
          header: {
            'content-type': 'application/json', // 默认值
            Authorization: userStore.token
          },
          success: function (response) {
            // console.log(response.data, '请求成功')
            // 在此处理其他逻辑
            sb(response.data.data)
          },
          fail: function (error) {
            console.error(error, '请求失败')
            // 在此处理错误情况
          }
        })
      } else {
        console.log('登录失败！' + res.errMsg)
      }
    }
  })
}
//下载qqmap-wx-jssdk,然后引入其中的js文件
let QQMapWX = require("../../assets/js/qqmap-wx-jssdk.min.js");

let qqmapsdk = new QQMapWX({
  key: "27FBZ-YPHH4-6M4UP-KLBGA-67TAV-UBBE2", // 必填
});
//  地址解析
const GETLNGLAT = (address) => {
  qqmapsdk.geocoder({
    address,
    success: (res) => {
      // console.log(res, 269)
      const { lat: latitude, lng: longitude } = res.result.location
      console.log(latitude, longitude)

      Taro.chooseLocation({
        longitude,
        latitude,
        success(res) {
          const latitude = res.latitude
          const longitude = res.longitude

          const addressName = res.name
          //逆地址解析,通过经纬度获取位置等信息
          qqmapsdk.reverseGeocoder({
            location: { latitude, longitude },
            success: function (res) {
              console.log(res, 285)

              // const province = res.result.address_component.province //省
              // const city = res.result.address_component.city //市
              // const district = res.result.address_component.district //区

              // addressInfo.value = [province, city, district]
              // formData.value.address = addressName
            },
            fail: function (res) {
              console.log(res)
            }
          })
        }
      })
    }
  })
}
async function sb(openid) {
  // console.log(openid, 'openid')
  let params = {
    openid,
    content: autoAddressInfo.value
  }
  const res: any = await $post('http://it.shenghui56.com/serversh/general/address/resolution', params)
  const data1 = res.data.data[0]
  // console.log(data1, 352)
  let adjustedAddress = adjustDistrict(data1.xzq.province, data1.xzq.city, data1.xzq.district)
  // console.log(adjustedAddress, 355)

  if (adjustedAddress.county.substr(-1) == '市' && data1.address.charAt(0)) {
    addressForm.value.address = data1.address.replace(data1.address.charAt(0), '')
  } else {
    addressForm.value.address = data1.address
  }

  addressForm.value.name = data1.name
  addressForm.value.phone = data1.mobile && data1.mobile[0]
  addressForm.value.provinceAdd = [adjustedAddress.province, adjustedAddress.city, adjustedAddress.county].join()
  addressInfo.value = [adjustedAddress.province, adjustedAddress.city, adjustedAddress.county]
}

onMounted(() => {
  if (process.env.TARO_ENV === 'weapp') {
    initRecord()
  }
})

// 图片识别 
// const upLoadImg = ()=> {
//   Taro.chooseImage({
//     count: 1,
//     sizeType: 'original',
//     success: async (res)=>{
//       console.log(res.tempFilePaths[0])
//       Taro.showLoading({
//         title: '识别中',
//       })
//       return
//       const imgRes = await $upload2('/selfmachine-system/image/pictureAnalysis','file', res.tempFilePaths[0])
//       Taro.hideLoading()
//       const resData = JSON.parse(imgRes.data)
//       if(resData.code ==200){
//         Taro.showToast({
//           icon: 'none',
//           title: '图片识别成功'
//         })
//         autoAddressInfo.value = resData.data
//       }
//     },
//     fail: (err)=>{
//       Taro.hideLoading()
//       // Taro.showToast({
//       //   icon: 'error',
//       //   title: '图片识别失败'
//       // })
//     }
//   })
// }
</script>

<style lang="scss">
.address_icon {
  width: 70rpx;
  height: 70rpx;
  line-height: 100rpx;
  background: url(../../assets/images/index/服务查询/wangdianchaxun_icon_chakanditu@2x.png) no-repeat center;
  margin-right: 25rpx;
}

.flex-ld {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
}

.sb {
  background-color: white;
  width: 100%;
  height: 216rpx;
  border-radius: 24rpx;
  border-bottom: 16rpx #f5f5f5 solid;

  .nut-textarea {
    border-radius: 24rpx;
    padding: 20rpx 30rpx;
  }

  .row {
    width: 100%;
    height: 56rpx;
    // background-color: red;
    display: flex;

    .one {
      width: calc(100% - 201rpx);
      height: 100%;
      display: flex;
      align-items: center;
      padding-left: 24rpx;
      box-sizing: border-box;

      image {
        width: 32rpx;
        height: 32rpx;
      }

      .text {
        font-size: 24rpx;
        font-family: PingFangSC-Regular;
      }
    }

    .tow {
      width: 176rpx;
      height: 100%;

      .button {
        width: 176rpx;
        height: 56rpx;
        border-radius: 28rpx;
        background: #0966ff;

        font-family: PingFang SC Bold;
        font-size: 26rpx;
        color: #ffffff;
        text-align: center;
        line-height: 56rpx;
      }
    }
  }
}

.address_del {
  border-radius: 24rpx;
  background-color: white;
  width: 702rpx;
  margin-left: 24rpx;
  margin-top: 16rpx;
  border-bottom: 16rpx #f5f5f5 solid;

  .footRows {
    width: 702rpx;
    height: 104rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .default_address {
      display: flex;
      justify-content: space-between;
      height: 50rpx;
      align-items: center;
      padding: 20rpx;

      .nut-checkbox__label {
        margin-left: 10rpx;
        font-family: PingFangSC-Regular;
        font-size: 24rpx;
        color: #666666;
      }
    }

    .clear {
      margin-right: 50rpx;
      color: #666;
      font-family: PingFangSC-Regular;
      font-size: 24rpx;
      display: flex;

      span {
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>
